import sls_coordinationConvert
from PyQt6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton, QListWidget,QHBoxLayout,QListWidgetItem,
    QSplitter, QDialog,QInputDialog
)
from PyQt6.QtGui import QBrush,QColor
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QDialog
import sys
from sls_uavNormalMissions.sls_uavMissionsTakeoff import Ui_MissionsTakeoff
from sls_uavNormalMissions.sls_uavMissionsLand import Ui_MissionsLand
from sls_uavNormalMissions.sls_uavMissionsPurePursuit import Ui_MissionsPurePursuit
from sls_uavNormalMissions.sls_uavMissionsDroneDirectPursuitCar import Ui_MissionsDroneDirectPursuitCar

class ngc_NormalMissions(QWidget):
    def __init__(self,parent,index:int=-1):
        super().__init__()
        self.add_index = index      
        self.parent = parent
        self.id = parent.id
        self.mirror_agent = parent.mirror_agent
        self.notifyClass = parent.notifyClass
    
    def add_mission(self,takeoffDict):
        if self.add_index == -1:
            self.mirror_agent.append_mission_to_schedule(self.id,takeoffDict)
        else:
            self.mirror_agent.add_mission_to_schedule(self.id,takeoffDict,self.add_index)    
        #更新列表
        self.mirror_agent.request_scheduleUpdate_missions_list(self.id)
    
    def close_window(self):
        self.close()


class ngc_MisssionsTakeoff(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.ui = Ui_MissionsTakeoff()
        self.ui.setupUi(self)
        self.setWindowTitle(f"{self.id} 起飞")
        self.ui.okpushButton.clicked.connect(self.pushButton_clicked)
        self.ui.checkBox.stateChanged.connect(self.checkBox_stateChanged)

    def checkBox_stateChanged(self, state):
        if state == 2:  # 选中状态
            self.ui.yawSpinBox.setEnabled(False)  # 禁用 yawSpinBox
        else:  # 未选中状态
            self.ui.yawSpinBox.setEnabled(True)  # 启用 yawSpinBox

    def pushButton_clicked(self):
        takeoff_altitude = self.ui.altitudeSpinBox.value()
        if self.ui.checkBox.isChecked():
            yaw = None
        else:
            yaw = self.ui.yawSpinBox.value()
        #组合并发送
        takeoffDict = {
            "missionsType": "MissionsTakeoff",
            "datasets":{
                "takeoff_relative_altitude": takeoff_altitude,
                "yaw": yaw
            }      
        }

        self.add_mission(takeoffDict)
        self.close_window()

class ngc_MisssionsLand(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.ui = Ui_MissionsLand()
        self.ui.setupUi(self)
        self.setWindowTitle(f"{self.id} 原地降落")
        self.ui.okpushButton.clicked.connect(self.pushButton_clicked)
        self.ui.checkBox.stateChanged.connect(self.checkBox_stateChanged)

    def checkBox_stateChanged(self, state):
        if state == 2:  # 选中状态
            self.ui.yawSpinBox.setEnabled(False)  # 禁用 yawSpinBox
        else:  # 未选中状态
            self.ui.yawSpinBox.setEnabled(True)  # 启用 yawSpinBox

    def pushButton_clicked(self):
        detection_time = self.ui.altitudeSpinBox.value()
        if self.ui.checkBox.isEnabled:
            yaw = None
        else:
            yaw = self.ui.yawSpinBox.value()
        #组合并发送
        landDict = {
            "missionsType": "MissionsLand",
            "datasets":{
                "landing_detection_time": detection_time,
                "yaw": yaw
            }
        }

        self.add_mission(landDict)
        self.close_window()

class ngc_MissionsPurePursuit(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.setWindowFlags(Qt.WindowType.WindowStaysOnTopHint)
        self.ui = Ui_MissionsPurePursuit()
        self.ui.setupUi(self)
        self.setWindowTitle(f"{self.id} 纯跟踪")
        self.ui.pushButton.clicked.connect(self.pushButton_clicked)
        self.notifyClass.add_notify_Cordinate(self.on_click_point)

    def on_click_point(self,latitude,longitude):
        self.parent.parent.add_marker(latitude,longitude,f'{self.id}temppoint')
        self.longitude,self.latitude = longitude,latitude
        #在界面显示显示WGS84坐标
        self.ui.positionLabel.setText(f"WGS84坐标，经度：{self.longitude} 纬度：{self.latitude}")

    def pushButton_clicked(self):
        #删点
        self.parent.parent.del_marker(f'{self.id}temppoint')
        #组合并发送
        purePursuitDict = {
            "missionsType": "MissionsPurePursuit",
            "datasets":{
                "latitude":self.latitude,
                "longitude":self.longitude,
            }
        }
        self.add_mission(purePursuitDict)
        self.close_window()

    def closeEvent(self, event):
        self.notifyClass.remove_notify_Cordinate(self.on_click_point)
        
class ngc_MisssionsDroneDirectPursuitCar(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.ui = Ui_MissionsDroneDirectPursuitCar()
        self.ui.setupUi(self)
        self.setWindowTitle(f"{self.id} 无人机跟踪无人车")
        self.ui.okpushButton.clicked.connect(self.pushButton_clicked)
    
    def pushButton_clicked(self):
      
        #组合并发送
        DroneDirectPursuitCarDict = {
            "missionsType": "MissionsDroneDirectPursuitCar",
            "datasets":None
        }

        self.add_mission(DroneDirectPursuitCarDict)
        self.close_window()

class ngc_MissionsLifecycleActivate(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.resize(400,300)

        self.setWindowTitle(f"{self.id} 激活任务")
        self.topList = QListWidget()
        self.topList.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)  # 多选
        self.topList.setDragEnabled(True)
        self.topList.setAcceptDrops(True)
        self.topList.setDropIndicatorShown(True)
        self.topList.setDefaultDropAction(Qt.DropAction.MoveAction)
        self.topList.setDragDropMode(QListWidget.DragDropMode.DragDrop)

        self.bottomList = QListWidget()
        self.bottomList.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)  # 多选
        self.bottomList.setDragEnabled(True)
        self.bottomList.setAcceptDrops(True)
        self.bottomList.setDropIndicatorShown(True)
        self.bottomList.setDefaultDropAction(Qt.DropAction.MoveAction)
        self.bottomList.setDragDropMode(QListWidget.DragDropMode.DragDrop)

        item1 = QListWidgetItem("打开底部摄像头")
        item1.setData(Qt.ItemDataRole.UserRole, "open_bottom_camera")
        self.bottomList.addItem(item1)

        item2 = QListWidgetItem("打开激光传感器")
        item2.setData(Qt.ItemDataRole.UserRole, "open_laser_sensor")
        self.bottomList.addItem(item2)

        item3 = QListWidgetItem("test")
        item3.setData(Qt.ItemDataRole.UserRole, "lc_talker")
        self.bottomList.addItem(item3)

        enter_PushButton = QPushButton("确认")
        # reset_PushButton = QPushButton("重置")
        cancel_PushButton = QPushButton("取消")
        Hlayout = QHBoxLayout()
        Hlayout.addStretch()
        Hlayout.addWidget(enter_PushButton)
        # Hlayout.addWidget(reset_PushButton)
        Hlayout.addWidget(cancel_PushButton)

        Vlayout = QVBoxLayout()
        Vlayout.addWidget(self.topList)
        Vlayout.addWidget(self.bottomList)
        Vlayout.addLayout(Hlayout)
        self.setLayout(Vlayout)

        enter_PushButton.clicked.connect(self.enter_PushButton_callback)
        # reset_PushButton.clicked.connect(self.reset_PushButton_callback)
        cancel_PushButton.clicked.connect(self.cancel_PushButton_callback)

    def enter_PushButton_callback(self):
        mission_list = []
        for i in range(self.topList.count()):
            item = self.topList.item(i)
            logic_id = item.data(Qt.ItemDataRole.UserRole)
            mission_list.append(logic_id)
        missionsLifecycleActivateDict = {"missionsType":"MissionsUAVLifecycleActivate","datasets":mission_list}
        print(missionsLifecycleActivateDict)
        self.add_mission(missionsLifecycleActivateDict)
        self.close_window()
    # def reset_PushButton_callback(self):
    #     pass

    def cancel_PushButton_callback(self):
        self.close_window()

class ngc_MissionsAddUGVTask(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.resize(400,300)

        self.setWindowTitle(f"{self.id} 添加无人车任务")
        self.topList = QListWidget()
        self.topList.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)  # 多选
        self.topList.setDragEnabled(True)
        self.topList.setAcceptDrops(True)
        self.topList.setDropIndicatorShown(True)
        self.topList.setDefaultDropAction(Qt.DropAction.MoveAction)
        self.topList.setDragDropMode(QListWidget.DragDropMode.DragDrop)

        self.bottomList = QListWidget()
        self.bottomList.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)  # 多选
        self.bottomList.setDragEnabled(True)
        self.bottomList.setAcceptDrops(True)
        self.bottomList.setDropIndicatorShown(True)
        self.bottomList.setDefaultDropAction(Qt.DropAction.MoveAction)
        self.bottomList.setDragDropMode(QListWidget.DragDropMode.DragDrop)

        item1 = QListWidgetItem("无人车跟踪无人机")
        item1.setData(Qt.ItemDataRole.UserRole, "MissionsCarFollowDrone")
        self.bottomList.addItem(item1)

        item2 = QListWidgetItem("测试任务（勿删）")
        item2.setData(Qt.ItemDataRole.UserRole, "MissionsSimple")
        self.bottomList.addItem(item2)

        enter_PushButton = QPushButton("确认")
        cancel_PushButton = QPushButton("取消")
        Hlayout = QHBoxLayout()
        Hlayout.addStretch()
        Hlayout.addWidget(enter_PushButton)
        Hlayout.addWidget(cancel_PushButton)
        Vlayout = QVBoxLayout()
        Vlayout.addWidget(self.topList)
        Vlayout.addWidget(self.bottomList)
        Vlayout.addLayout(Hlayout)
        self.setLayout(Vlayout)
        self.bottomList.itemDoubleClicked.connect(self.item_double_clicked)
        self.topList.itemDoubleClicked.connect(self.item_double_clicked)
        enter_PushButton.clicked.connect(self.enter_PushButton_callback)
        cancel_PushButton.clicked.connect(self.cancel_PushButton_callback)

        self.mission_list_dict = []
    def item_double_clicked(self,item: QListWidgetItem):
        mission_id = item.data(Qt.ItemDataRole.UserRole)
        if mission_id == "MissionsSimple":
            for i in self.mission_list_dict:
                i:dict
                if i.get("missionsType") == "MissionsSimple":
                    self.mission_list_dict.remove(i)
            param,ok = QInputDialog.getText(self, "参数设置","请输入MissionsSimple的参数")
            self.mission_list_dict.append({"missionsType":"MissionsSimple","datasets":int(param)})
            # print(self.mission_list_dict)

    def enter_PushButton_callback(self):
        mission_list = []
        for i in range(self.topList.count()):
            item = self.topList.item(i)
            logic_id = item.data(Qt.ItemDataRole.UserRole)
            mission_list.append({"missionsType":logic_id,"datasets":None})
        exclude_types = {item["missionsType"] for item in self.mission_list_dict}
        mission_list = [item for item in mission_list 
                    if item["missionsType"] not in exclude_types]
        mission_list += self.mission_list_dict
        bottom_logic_ids = {
                self.bottomList.item(i).data(Qt.ItemDataRole.UserRole) 
                for i in range(self.bottomList.count())
            }
        mission_list = [
            item for item in mission_list 
            if item["missionsType"] not in bottom_logic_ids
        ]
        missionsAddUGVTasksDict = {"missionsType":"MissionsAddUGVTasks","datasets":mission_list}
        # print(missionsLifecycleActivateDict)
        self.add_mission(missionsAddUGVTasksDict)
        self.close_window()
    # def reset_PushButton_callback(self):
    #     pass

    def cancel_PushButton_callback(self):
        self.close_window()

class ngc_MissionsUAVFinishedFlag(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.setWindowTitle(f"{self.id} add flag")
        enter_PushButton = QPushButton("确认")
        Hlayout = QHBoxLayout()
        Hlayout.addStretch()
        Hlayout.addWidget(enter_PushButton)
        Hlayout.addStretch()
        self.setLayout(Hlayout)
        enter_PushButton.clicked.connect(self.enter_PushButton_callback)
    def enter_PushButton_callback(self):
        missionsUAVFinishedFlagDict = {"missionsType":"MissionsUAVFinishedFlag","datasets":None}
        self.add_mission(missionsUAVFinishedFlagDict)
        self.close_window()

class ngc_MissionsQRLand(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1,):
        super().__init__(parent,index)
        self.auto_mission()
    def auto_mission(self):
        mission_data = {"missionsType": "MissionsQRLand", "datasets": None}
        self.add_mission(mission_data)
        self.close_window()

from PyQt6.QtWidgets import (
    QLabel, QDoubleSpinBox, QCheckBox, QPushButton, QVBoxLayout, QHBoxLayout, QWidget
)
class ngc_MissionsHover(ngc_NormalMissions):
    def __init__(self, parent, index: int = -1):
        super().__init__(parent, index)
        self.setWindowTitle(f"{self.id} 悬停任务")
        self.resize(250, 300)

        # === 创建控件 ===
        self.altitudeLabel = QLabel("悬停高度 (m):")
        self.altitudeSpinBox = QDoubleSpinBox()
        self.altitudeSpinBox.setRange(0.0, 50.0)
        self.altitudeSpinBox.setSingleStep(0.1)
        self.altitudeSpinBox.setValue(3.0)

        self.durationLabel = QLabel("悬停时间 (s):")
        self.durationSpinBox = QDoubleSpinBox()
        self.durationSpinBox.setRange(0.0, 600.0)
        self.durationSpinBox.setSingleStep(1.0)
        self.durationSpinBox.setValue(10.0)

        self.yawLabel = QLabel("悬停朝向 (°):")
        self.yawSpinBox = QDoubleSpinBox()
        self.yawSpinBox.setRange(-180.0, 180.0)
        self.yawSpinBox.setSingleStep(1.0)
        self.yawSpinBox.setValue(0.0)

        self.checkBox = QCheckBox("使用当前航向")
        self.okpushButton = QPushButton("确认")
        self.cancelpushButton = QPushButton("取消")

        # === 布局 ===
        layout = QVBoxLayout()
        layout.addWidget(self.altitudeLabel)
        layout.addWidget(self.altitudeSpinBox)
        layout.addWidget(self.durationLabel)
        layout.addWidget(self.durationSpinBox)
        layout.addWidget(self.yawLabel)
        layout.addWidget(self.yawSpinBox)
        layout.addWidget(self.checkBox)
        layout.addStretch()
        layout.addStretch()

        hlayout = QHBoxLayout()
        hlayout.addStretch()
        hlayout.addWidget(self.okpushButton)
        hlayout.addWidget(self.cancelpushButton)
        hlayout.addStretch()
        layout.addLayout(hlayout)

        self.setLayout(layout)

        # === 信号槽连接 ===
        self.okpushButton.clicked.connect(self.pushButton_clicked)
        self.cancelpushButton.clicked.connect(self.close_window)
        self.checkBox.stateChanged.connect(self.checkBox_stateChanged)

    def checkBox_stateChanged(self, state):
        self.yawSpinBox.setEnabled(state != 2)

    def pushButton_clicked(self):
        hover_alt = self.altitudeSpinBox.value()
        duration = self.durationSpinBox.value()
        yaw = None if self.checkBox.isChecked() else self.yawSpinBox.value()

        # 组合任务字典
        hoverDict = {
            "missionsType": "MissionsHover",
            "datasets": {
                "target_altitude": hover_alt,
                "hover_duration": duration,
                # "yaw": yaw
            }
        }

        # 发送到 mirror_agent
        self.add_mission(hoverDict)
        self.close_window()

missions_table={"MissionsTakeoff":ngc_MisssionsTakeoff,
                "MissionsLand":ngc_MisssionsLand,
                "MissionsPurePursuit":ngc_MissionsPurePursuit,
                "MissionsDroneDirectPursuitCar":ngc_MisssionsDroneDirectPursuitCar,
                "MissionsUAVLifecycleActivate":ngc_MissionsLifecycleActivate,
                "MissionsUAVFinishedFlag":ngc_MissionsUAVFinishedFlag,
                "MissionsAddUGVTask":ngc_MissionsAddUGVTask,
                "MissionsQRLand":ngc_MissionsQRLand,
                "MissionsHover": ngc_MissionsHover,
                }
